import tools from "../tools"
import HashList from "./hash.list.js"
import SetList from "./set.list.js"
import ZSetList from "./zset.list.js"
import ListList from "./list.list.js"
export default class KeyDetail extends Element {
    key = null
    constructor() {
        super()
        document.on("db-change", () => {
            this.key = null
        })
        document.on("key-change", (evt) => {
            try {
                this.key = evt.data.key
                window.redis_key = evt.data.key
                this.getKeyInfo()
            } catch (e) {

            }

        })
    }
    /**
     * 重置初始化数据
     */
    resetInitData() {
        this.key = null
        this.info = []
    }
    /**
     * 刷新key列表
     */
    refreshKeyList() {
        this.post(new Event("refresh-key-list", {bubbles: true}))
        this.getKeyInfo()
    }
    /**
     * 获取key信息
     */
    getKeyInfo() {
        if (!this.key) {
            return
        }
        setTimeout(()=>{
            tools.xcall("async_get_infos", this.key, parseInt(window.databaseInfo.Server.redis_version), data => {
                this.info = data.split(",")
                if (this.info[0] === "") {
                    this.resetInitData()
                }
                this.fetchKeyData(this.info[0])
                this.componentUpdate()
            })
        })
    }
    stringVal = ""
    fetchKeyData() {
        this.hashSearchKey = ""
        this.stringVal = ""
        tools.async_xcall("async_get_string_val", this.key)
            .then(res => {
                this.stringVal = res
                this.componentUpdate()
            })
    }
    /**
     * 新增key
     */
    addKey() {
        setTimeout(() => {
            let [x, y] = tools.windowPosition()
            let [w, h] = tools.windowSize()
            let scale = devicePixelRatio
            let width = 320 * scale
            let height = 230 * scale
            let modal = tools.getView().modal({
                width,
                height,
                x: x + w / 2 - width  / 2,
                y: y + h / 2 - height / 2,
                url: "/redis/maintain_key.html",
                parameters: {
                    title: "新增key",
                    view: tools.getView()
                }
            })
            if (modal === true) {
                this.refreshKeyList()
            }
        })
    }
    /**
     * 删除key
     */
    deleteKey() {
        if (!this.key) {
            return
        }
        tools.confirm("确定要删除吗？")
            .then(res => {
                if (res === true) {
                    let res = tools.xcall("delete_key", this.key)
                    if (res) {
                        tools.alert("删除成功")
                            .then(() => {
                                this.resetInitData()
                                this.refreshKeyList()
                                this.componentUpdate()
                            })
                    } else {
                        tools.alert("删除失败")
                    }
                }
            })

    }
    /**
     * 重命名
     */
    renameKey() {
        if (!this.key) {
            return
        }
        setTimeout(() => {
            const [x, y] = tools.windowPosition()
            const [w, h] = tools.windowSize()
            const scale = devicePixelRatio
            const width = 320 * scale
            const height = 200 * scale
            let modal = tools.getView().modal({
                width,
                height,
                x: x + w / 2 - width / 2,
                y: y + h / 2 - height / 2,
                url: "/redis/rename_key.html",
                parameters: {
                    title: "重命名key",
                    view: tools.getView(),
                    key: this.key
                }
            })
            if (modal.key) {
                this.key = modal.key
                this.getKeyInfo()
                this.refreshKeyList()
            }
        })

    }
    /**
     * 设置过期时间
     */
    ttlKey() {
        if (!this.key) {
            return
        }
        setTimeout(() => {
            let [x, y] = tools.windowPosition()
            let [w, h] = tools.windowSize()
            const scale = devicePixelRatio
            const width = 320 * scale
            const height = 240 * scale
            let modal = tools.getView().modal({
                width,
                height,
                x: x + w / 2 - width / 2,
                y: y + h / 2 - height / 2,
                url: "/redis/expire_key.html",
                parameters: {
                    title: "重设过期时间",
                    view: tools.getView(),
                    key: this.key
                }
            })
            if (modal === true) {
                this.getKeyInfo()
            }
        })
    }
    /**
     * 渲染string类型的数据
     */
    renderString() {
        return <div class="key-result">
            <b><code>{this.key}</code>的查询结果：</b>
            <br/>
            <div class="string">
                <div class="copy" onClick={() => this.doCopy(this.stringVal)}>复制</div>
                <div style="margin:3px 8px">{this.stringVal}</div>
            </div>
        </div>
    }
    /**
     * 执行复制功能
     * @param val
     */
    doCopy(val) {
        Clipboard.writeText(val)
    }
    /**
     * 导出数据
     */
    exportFile(data) {
        let file = tools.getView().selectFile({
            mode: "save",
            filter: "JSON文件|*.json",
            caption: `保存为`,
            path: `${this.key}.json`
        })
        if (file) {
            tools.sys.fs.open(file.slice(7), "wb+")
                .then(fd => {
                    return fd.write(data)
                })
                .then(() => {
                    tools.alert("保存成功！")
                })
                .catch(e => {
                    tools.alert("保存失败：" + e.message)
                })
        }
    }
    /**
     * list类型渲染
     * @returns {JSX.Element}
     */
    renderList() {
        return <ListList />
    }
    timer = -1

    /**
     * 渲染set数据
     * @returns {JSX.Element}
     */
    renderSet() {
        return <div class="list-info">
            <div class="list-info-title">
                <span><b>{this.key}</b>查询结果</span>
                <div class="list-info-title-action">
                    <input type="text" class="hash-search" placeholder="为空则查询全部" onChange={(evt, ele) => {
                        this.setSearchKey = ele.value
                        clearTimeout(this.timer)
                        this.timer = setTimeout(() => {
                            if (ele.value === "") {
                                this.post(new Event("set-search", {bubbles: true, data: {key: this.setSearchKey}}))
                            }
                        }, 200)
                    }}/>
                    <div class="btn" onClick={() => {
                        this.post(new Event("set-search", {bubbles: true, data: {key: this.setSearchKey}}))
                    }}>查询
                    </div>
                    <div class="btn" onClick={() => {
                        setTimeout(() => {
                            let [x, y] = tools.windowPosition()
                            let [w, h] = tools.windowSize()
                            let scale = devicePixelRatio
                            let width = 320 * scale
                            let height = 200 * scale
                            let modal = tools.getView().modal({
                                width,
                                height,
                                x: x + w / 2 - width  / 2,
                                y: y + h / 2 - height / 2,
                                url: "/redis/append_set_value.html",
                                parameters: {
                                    title: "插入新值",
                                    view: tools.getView(),
                                    key: this.key
                                }
                            })
                            if (modal === true) {
                                this.componentUpdate()
                            }
                        })

                    }}>新增
                    </div>
                    <div class="btn" onClick={() => {
                        this.exportFile(JSON.stringify(this.setData))
                    }}>导出
                    </div>
                </div>
            </div>
            <div class="table">
                <div class="tr">
                    <div class="th v v-index">#</div>
                    <div class="th k">值</div>
                    <div class="th v v-a v-s-a">操作</div>
                </div>
                <div class="hash-body">
                    {<SetList/>}
                </div>
            </div>
        </div>
    }

    /**
     * 渲染hash数据
     * @returns {JSX.Element}
     */
    renderHash() {
        return <div class="list-info">
            <div class="list-info-title">
                <span><b>{this.key}</b>查询结果</span>
                <div class="list-info-title-action">
                    <input type="text" class="hash-search" placeholder="为空则查询全部" onChange={(evt, ele) => {
                        this.hashSearchKey = ele.value
                        clearTimeout(this.timer)
                        this.timer = setTimeout(() => {
                            if (ele.value === "") {
                                this.post(new Event("hash-search", {bubbles: true, data: {key: this.hashSearchKey}}))
                            }
                        }, 200)
                    }}/>
                    <div class="btn" onClick={() => {
                        this.post(new Event("hash-search", {bubbles: true, data: {key: this.hashSearchKey}}))
                    }}>查询
                    </div>
                    <div class="btn" onClick={() => {
                        setTimeout(() => {
                            let [x, y] = tools.windowPosition()
                            let [w, h] = tools.windowSize()
                            let scale = devicePixelRatio
                            let width = 320 * scale
                            let height = 240 * scale
                            let modal = tools.getView().modal({
                                width,
                                height,
                                x: x + w / 2 - width  / 2,
                                y: y + h / 2 - height / 2,
                                url: "/redis/append_hash_exist_key_value.html",
                                parameters: {
                                    title: "插入新值",
                                    view: tools.getView(),
                                    key: this.key
                                }
                            })
                            if (modal === true) {
                                this.post(new Event("hash-refresh", {bubbles: true}))
                            }
                        })

                    }}>新增
                    </div>
                    <div class="btn" onClick={() => {
                        tools.xcall("async_get_hash_data", this.key,"*", res => {
                            if (res.code !== 200) {
                                return
                            }
                            this.exportFile(JSON.stringify(res.data))
                        })
                    }}>导出
                    </div>
                </div>
            </div>
            <div class="table">
                <div class="tr">
                    <div class="th v v-field">字段</div>
                    <div class="th k">值</div>
                    <div class="th v v-a">操作</div>
                </div>
                <div class="hash-body">
                    {<HashList/>}
                </div>
            </div>
        </div>
    }

    renderZSet(){
        return <div class="list-info">
            <div class="list-info-title">
                <span><b>{this.key}</b>查询结果</span>
                <div class="list-info-title-action">
                    <input type="text" class="hash-search" placeholder="为空则查询全部" onChange={(evt, ele) => {
                        this.hashSearchKey = ele.value
                        clearTimeout(this.timer)
                        this.timer = setTimeout(() => {
                            if (ele.value === "") {
                                this.post(new Event("zset-search", {bubbles: true, data: {key: this.hashSearchKey}}))
                            }
                        }, 200)
                    }}/>
                    <div class="btn" onClick={() => {
                        this.post(new Event("zset-search", {bubbles: true, data: {key: this.hashSearchKey}}))
                    }}>查询
                    </div>
                    <div class="btn" onClick={() => {
                        setTimeout(() => {
                            let [x, y] = tools.windowPosition()
                            let [w, h] = tools.windowSize()
                            let scale = devicePixelRatio
                            let width = 320 * scale
                            let height = 240 * scale
                            let modal = tools.getView().modal({
                                width,
                                height,
                                x: x + w / 2 - width  / 2,
                                y: y + h / 2 - height / 2,
                                url: "/redis/append_zset_value.html",
                                parameters: {
                                    title: "插入新值",
                                    view: tools.getView(),
                                    key: this.key
                                }
                            })
                            if (modal === true) {
                                this.post(new Event("zset-refresh", {bubbles: true}))
                            }
                        })

                    }}>新增
                    </div>
                    <div class="btn" onClick={() => {
                        tools.xcall("async_search_z_set_member", this.key,"*", res => {
                            if (res.code === 200) {
                                this.exportFile(JSON.stringify(res.data))
                            } else {
                                tools.alert(res.msg,{type:"error"})
                            }
                        })
                    }}>导出
                    </div>
                </div>
            </div>
            <div class="table">
                <div class="tr">
                    <div class="th v v-field">成员</div>
                    <div class="th k">值</div>
                    <div class="th v v-a">操作</div>
                </div>
                <div class="hash-body">
                    {<ZSetList/>}
                </div>
            </div>
        </div>
    }
    renderUnknown() {
        return <div class="key-result">
            <h1>Sorry {this.info[1]} not support yet.</h1>
        </div>
    }

    renderResult() {
        switch (this.info[0]) {
            case "string":
                return this.renderString()
            case "list":
                return this.renderList()
            case "set":
                return this.renderSet()
            case "hash":
                return this.renderHash()
            case "zset":
                return this.renderZSet()
            default:
                return this.renderUnknown()
        }
    }

    renderKeyInfo() {
        if (!this.key) {
            return <div class="key-detail-container-none">
                <span>Not choose a key</span>
            </div>
        }
        return <div class="key-detail-container">
            <div class="key-info">
                <div class="key-info-title">
                    Key基础信息
                </div>
                <div class="table">
                    <div class="tr">
                        <div class="th k">键</div>
                        <div class="th v">类型</div>
                        <div class="th v">大小</div>
                        <div class="th v v-t">TTL(毫秒)</div>
                    </div>
                    <div class="tr">
                        <div class="td k">{this.key}
                            <div class="key-copy" onClick={() => this.doCopy(this.key)}>复制</div>
                        </div>
                        <div class="td v">{this.info[0]}</div>
                        <div class="td v">{this.info[1]}</div>
                        <div class="td v v-t">{this.info[2]}</div>
                    </div>
                </div>
            </div>
            {this.renderResult()}
        </div>
    }

    render() {
        return <div class={"key-detail"}>
            <div class={"key-detail-actions"}>
                <button class="action-btn" onClick={() => this.addKey()}>
                    <i class="icon icon-plus"></i>
                    <span>新增</span>
                </button>
                <button class="action-btn" onClick={() => this.renameKey()}>
                    <i class="icon icon-pencil"></i>
                    <span>重命名</span>
                </button>
                <button class="action-btn" onClick={() => this.ttlKey()}>
                    <i class="icon icon-av-timer"></i>
                    <span>TTL</span>
                </button>
                <button class="action-btn" onClick={() => this.deleteKey()}>
                    <i class="icon icon-delete-forever"></i>
                    <span>删除</span>
                </button>
                <button class="action-btn" onClick={() => this.getKeyInfo()}>
                    <i class="icon icon-refresh"></i>
                    <span>刷新</span>
                </button>
            </div>
            {this.renderKeyInfo()}
        </div>
    }
}